package com.car.loan.project.xr.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.car.loan.common.exception.loan.LoanParameterException;
import com.car.loan.common.utils.BeanUtils;
import com.car.loan.common.utils.SecurityUtils;
import com.car.loan.common.utils.StringUtils;
import com.car.loan.common.utils.qiniu.QiniuUtil;
import com.car.loan.framework.web.domain.AjaxResult;
import com.car.loan.project.xr.domain.Customer;
import com.car.loan.project.xr.domain.Loan;
import com.car.loan.project.xr.domain.LoanAlbum;
import com.car.loan.project.xr.domain.LoanCar;
import com.car.loan.project.xr.domain.LoanExt;
import com.car.loan.project.xr.domain.LoanInsurance;
import com.car.loan.project.xr.domain.LoanStatus;
import com.car.loan.project.xr.mapper.CustomerMapper;
import com.car.loan.project.xr.mapper.LoanAlbumMapper;
import com.car.loan.project.xr.mapper.LoanCarMapper;
import com.car.loan.project.xr.mapper.LoanExtMapper;
import com.car.loan.project.xr.mapper.LoanInsuranceMapper;
import com.car.loan.project.xr.mapper.LoanMapper;
import com.car.loan.project.xr.mapper.LoanStatusMapper;
import com.car.loan.project.xr.service.ILoanCarInfoService;
import com.car.loan.project.xr.util.RedisDataUtil;
import com.car.loan.project.xr.util.bo.business.CarInfoInputBo;
import com.car.loan.project.xr.util.bo.business.InsuranceInfoBo;
import com.car.loan.project.xr.util.bo.business.LicenseBaseInfoBo;
import com.car.loan.project.xr.util.bo.business.LoanAlbumBo;
import com.car.loan.project.xr.util.bo.business.MortgageInfoBo;
import com.car.loan.project.xr.util.enums.CarInfoStatus;
import com.car.loan.project.xr.util.enums.InsuranceInfoStatus;
import com.car.loan.project.xr.util.enums.LicenseInfoStatus;
import com.car.loan.project.xr.util.enums.LoanAlbumType;
import com.car.loan.project.xr.util.enums.MortgageInfoStatus;
import com.car.loan.project.xr.util.vo.CarInfoBaseVo;
import com.car.loan.project.xr.util.vo.CarInfoInputVo;
import com.car.loan.project.xr.util.vo.CustomerBaseInfoVo;
import com.car.loan.project.xr.util.vo.LoanAlbumVo;
import com.car.loan.project.xr.util.vo.LoanDetailVo.LoanBaseInfoVo;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;
import javax.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @author huangding
 * @description
 * @date 2019/12/22 12:39
 */
@Service
public class LoanCarInfoServiceImpl implements ILoanCarInfoService {

    @Autowired
    private RedisDataUtil redisDataUtil;

    @Autowired
    private CustomerMapper customerMapper;

    @Autowired
    private LoanMapper loanMapper;

    @Autowired
    private LoanCarMapper loanCarMapper;

    @Autowired
    private LoanExtMapper loanExtMapper;

    @Autowired
    private LoanStatusMapper loanStatusMapper;

    @Autowired
    private LoanAlbumMapper loanAlbumMapper;

    @Autowired
    private QiniuUtil qiniuUtil;

    @Resource
    private LoanInsuranceMapper loanInsuranceMapper;

    @Override
    public CarInfoInputVo getCarInfoInputVo(Long loanId) {

        CarInfoInputVo carInfoInputVo = new CarInfoInputVo();

        Optional<Loan> optionalLoan
            = Optional.ofNullable(loanMapper.selectById(loanId));
        Loan loan = optionalLoan.orElseThrow(() -> new LoanParameterException("无该业务数据"));
        //获取页面展示信息
        LoanBaseInfoVo loanBaseInfoVo = new LoanBaseInfoVo();
        loanBaseInfoVo.setAdminName(redisDataUtil.getAdminName(loan.getAdminId()));
        loanBaseInfoVo.setDealerName(
            redisDataUtil.getDealerName(loan.getDealerId()));
        loanBaseInfoVo.setDeptName(
            redisDataUtil.getDeptName(loan.getDeptId()));
        loanBaseInfoVo.setLoanNo(loan.getBusinessNo());
        carInfoInputVo.setLoanBaseInfo(loanBaseInfoVo);

//        //获取数据源
        Optional<LoanExt> optionalLoanExt = loanExtMapper.selectByLoanId(loanId);
        LoanExt loanExt = optionalLoanExt
            .orElseThrow(() -> new LoanParameterException("业务数据扩展信息异常"));

        Optional<LoanCar> optionalLoanCar = loanCarMapper.selectByLoanId(loanId);
        LoanCar loanCar = optionalLoanCar
            .orElseThrow(() -> new LoanParameterException("业务数据车辆信息异常"));

        //客户信息
        CustomerBaseInfoVo customerBaseInfoVo = new CustomerBaseInfoVo();
        Customer customer = customerMapper.selectById(loan.getCustomerId());
        customerBaseInfoVo.setName(customer.getName());
        customerBaseInfoVo.setMobile(customer.getMobile());
        customerBaseInfoVo.setIdCardNo(customer.getIdCardNo());
        customerBaseInfoVo.setIdType(customer.getIdType());
        carInfoInputVo.setCustomerBaseInfo(customerBaseInfoVo);

        //车辆信息
        CarInfoBaseVo carInfoBaseVo = new CarInfoBaseVo();
        carInfoBaseVo.setCarType(loanCar.getCarType());
        carInfoBaseVo.setCarNature(loanCar.getCarNature());
        carInfoBaseVo.setCarName(loanExt.getCarName());
        carInfoBaseVo.setRegistProvince(loanCar.getRegistProvince());
        carInfoBaseVo.setRegistCity(loanCar.getRegistCity());
        carInfoBaseVo.setSellAmount(loanExt.getSellAmount());
        carInfoBaseVo.setTerm(loanExt.getTerm());
        carInfoBaseVo.setBankName(redisDataUtil.getBankName(loan.getBankId()));

        carInfoBaseVo.setInstallmentAmount(loanExt.getInstallmentAmount());

        CarInfoInputBo carInfoInputBo = new CarInfoInputBo();
        carInfoInputBo.setLoanId(loan.getId().toString());
        BeanUtils.copyBeanProp(carInfoInputBo, loanCar);
        carInfoInputBo.setSellAmount(loanExt.getSellAmount());

        //获取附件信息
        LoanAlbum loanAlbumQuery = new LoanAlbum();
        loanAlbumQuery.setLoanId(loanId);
        loanAlbumQuery.setType(LoanAlbumType.CAR_INFO.type);
        QueryWrapper<LoanAlbum> loanAlbumQueryWrapper = new QueryWrapper<>(loanAlbumQuery);
        List<LoanAlbum> loanAlbums = loanAlbumMapper.selectList(loanAlbumQueryWrapper);
        if (StringUtils.isNotEmpty(loanAlbums)) {
            List<LoanAlbumVo> collect = loanAlbums.stream().map(
                l -> new LoanAlbumVo().setDbUrl(l.getUrl())
                    .setUrl(qiniuUtil.getAdminAuthUrl(l.getUrl()))
                    .setThumbnailUrl(qiniuUtil.getUrlByThumbnail(l.getUrl()))
                    .setType(l.getType())).collect(Collectors.toList());
            carInfoInputBo.setCarInfoAlbums(collect);
        }

        carInfoBaseVo.setCarInfoInput(carInfoInputBo);

        //保险信息
        InsuranceInfoBo insuranceInfoBo = new InsuranceInfoBo();
        Optional<LoanInsurance> loanInsuranceOptional = loanInsuranceMapper.selectByLoanId(loanId);
        BeanUtils.copyBeanProp(insuranceInfoBo, loanInsuranceOptional.get());
        carInfoBaseVo.setInsuranceInfo(insuranceInfoBo);
        //牌证信息
        LicenseBaseInfoBo licenseBaseInfoBo = new LicenseBaseInfoBo();
        BeanUtils.copyBeanProp(licenseBaseInfoBo, loanCar);
        carInfoBaseVo.setLicenseBaseInfo(licenseBaseInfoBo);
        //抵押信息
        MortgageInfoBo mortgageInfoBo = new MortgageInfoBo();
        mortgageInfoBo.setCertTransferDate(loanCar.getCertTransferDate());
        mortgageInfoBo.setMortgageDate(loanCar.getMortgageDate());
        carInfoBaseVo.setMortgageInfo(mortgageInfoBo);

        carInfoInputVo.setCarInfoBase(carInfoBaseVo);
        return carInfoInputVo;
    }

    @Override
    public AjaxResult input(CarInfoInputBo carInfoInputBo) {
        long loanId = Long.parseLong(carInfoInputBo.getLoanId());
        Optional<LoanStatus> optionalLoanStatus = loanStatusMapper
            .selectByLoanId(loanId);
        LoanStatus loanStatus = optionalLoanStatus
            .orElseThrow(() -> new LoanParameterException("业务状态数据异常请联系管理员"));
        if (CarInfoStatus.INIT.status != loanStatus.getCarInfoStatus()) {
            return AjaxResult.error("当前状态不可提交");
        }

        loanStatus.setCarInfoId(SecurityUtils.getLoginUserId());
        loanStatus.setCarInfoStatus(carInfoInputBo.getOperatorStatus());
        loanStatus.setCarInfoTime(LocalDateTime.now());
        loanStatusMapper.updateById(loanStatus);

        Optional<LoanCar> optionalLoanCar = loanCarMapper.selectByLoanId(loanId);
        LoanCar loanCar = optionalLoanCar
            .orElseThrow(() -> new LoanParameterException("业务数据车辆信息异常"));

        loanCar.setBankCarBrand(carInfoInputBo.getBankCarBrand());
        loanCar.setBankCarType(carInfoInputBo.getBankCarType());
        loanCar.setEngineNo(carInfoInputBo.getEngineNo());
        loanCar.setFrameNo(carInfoInputBo.getFrameNo());
        loanCar.setPlateType(carInfoInputBo.getPlateType());
        loanCar.setColor(carInfoInputBo.getColor());
        loanCar.setInvoiceDate(carInfoInputBo.getInvoiceDate());
        loanCar.setInvoiceUnit(carInfoInputBo.getInvoiceUnit());
        loanCar.setInvoicePrice(carInfoInputBo.getInvoicePrice());
        loanCar.setRegistOwner(carInfoInputBo.getRegistOwner());
        loanCarMapper.updateById(loanCar);

        Optional<LoanExt> optionalLoanExt = loanExtMapper.selectByLoanId(loanId);
        LoanExt loanExt = optionalLoanExt
            .orElseThrow(() -> new LoanParameterException("业务数据扩展信息异常"));

        loanExt.setSellAmount(carInfoInputBo.getSellAmount());
        loanExtMapper.updateById(loanExt);

        LoanAlbum loanAlbumDelete = new LoanAlbum();
        loanAlbumDelete.setLoanId(loanId);
        loanAlbumDelete.setType(LoanAlbumType.CAR_INFO.type);
        QueryWrapper<LoanAlbum> queryWrapper = new QueryWrapper<>(loanAlbumDelete);
        loanAlbumMapper.delete(queryWrapper);

        List<LoanAlbumVo> carInfoAlbums = carInfoInputBo.getCarInfoAlbums();
        if (null != carInfoAlbums) {
            carInfoAlbums.forEach(carInfoAlbum -> {
                LoanAlbum loanAlbum = new LoanAlbum();
                loanAlbum.setUrl(carInfoAlbum.getDbUrl());
                loanAlbum.setType(LoanAlbumType.CAR_INFO.type);
                loanAlbum.setLoanId(loanId);
                loanAlbumMapper.insert(loanAlbum);
            });
        }
        return AjaxResult.success();
    }

    @Override
    public synchronized  AjaxResult mortgageInput(MortgageInfoBo mortgageInfo) {

        long loanId = Long.parseLong(mortgageInfo.getLoanId());
        Optional<LoanStatus> optionalLoanStatus = loanStatusMapper
            .selectByLoanId(loanId);
        LoanStatus loanStatus = optionalLoanStatus
            .orElseThrow(() -> new LoanParameterException("业务状态数据异常请联系管理员"));
        if (MortgageInfoStatus.INIT.status != loanStatus.getMortgageInfoStatus()) {
            return AjaxResult.error("当前状态不可提交");
        }

        loanStatus.setMortgageInfoId(SecurityUtils.getLoginUserId());
        loanStatus.setMortgageInfoStatus(mortgageInfo.getOperatorStatus());
        loanStatus.setMortgageInfoTime(LocalDateTime.now());
        loanStatusMapper.updateById(loanStatus);

        Optional<LoanCar> optionalLoanCar = loanCarMapper.selectByLoanId(loanId);
        LoanCar loanCar = optionalLoanCar
            .orElseThrow(() -> new LoanParameterException("业务数据车辆信息异常"));

        loanCar.setMortgageDate(mortgageInfo.getMortgageDate());
        loanCar.setCertTransferDate(mortgageInfo.getCertTransferDate());
        loanCarMapper.updateById(loanCar);

        LoanAlbum loanAlbumDelete = new LoanAlbum();
        loanAlbumDelete.setLoanId(loanId);
        loanAlbumDelete.setType(LoanAlbumType.CAR_INFO.type);
        QueryWrapper<LoanAlbum> queryWrapper = new QueryWrapper<>(loanAlbumDelete);
        loanAlbumMapper.delete(queryWrapper);

        List<LoanAlbumVo> carInfoAlbums = mortgageInfo.getCarInfoAlbums();
        if (null != carInfoAlbums) {
            carInfoAlbums.forEach(carInfoAlbum -> {
                LoanAlbum loanAlbum = new LoanAlbum();
                loanAlbum.setUrl(carInfoAlbum.getDbUrl());
                loanAlbum.setType(LoanAlbumType.CAR_INFO.type);
                loanAlbum.setLoanId(loanId);
                loanAlbumMapper.insert(loanAlbum);
            });
        }
        return AjaxResult.success();
    }

    @Override
    public synchronized AjaxResult licenseInput(LicenseBaseInfoBo licenseBaseInfo) {
        long loanId = Long.parseLong(licenseBaseInfo.getLoanId());
        Optional<LoanStatus> optionalLoanStatus = loanStatusMapper
            .selectByLoanId(loanId);
        LoanStatus loanStatus = optionalLoanStatus
            .orElseThrow(() -> new LoanParameterException("业务状态数据异常请联系管理员"));
        if (LicenseInfoStatus.INIT.status != loanStatus.getLicenseInfoStatus()) {
            return AjaxResult.error("当前状态不可提交");
        }

        loanStatus.setLicenseInfoId(SecurityUtils.getLoginUserId());
        loanStatus.setLicenseInfoStatus(licenseBaseInfo.getOperatorStatus());
        loanStatus.setLicenseInfoTime(LocalDateTime.now());
        loanStatusMapper.updateById(loanStatus);

        Optional<LoanCar> optionalLoanCar = loanCarMapper.selectByLoanId(loanId);
        LoanCar loanCar = optionalLoanCar
            .orElseThrow(() -> new LoanParameterException("业务数据车辆信息异常"));
        BeanUtils.copyBeanProp(loanCar, licenseBaseInfo);
        loanCarMapper.updateById(loanCar);

        LoanAlbum loanAlbumDelete = new LoanAlbum();
        loanAlbumDelete.setLoanId(loanId);
        loanAlbumDelete.setType(LoanAlbumType.CAR_INFO.type);
        QueryWrapper<LoanAlbum> queryWrapper = new QueryWrapper<>(loanAlbumDelete);
        loanAlbumMapper.delete(queryWrapper);

        List<LoanAlbumVo> carInfoAlbums = licenseBaseInfo.getCarInfoAlbums();
        if (null != carInfoAlbums) {
            carInfoAlbums.forEach(carInfoAlbum -> {
                LoanAlbum loanAlbum = new LoanAlbum();
                loanAlbum.setUrl(carInfoAlbum.getDbUrl());
                loanAlbum.setType(LoanAlbumType.CAR_INFO.type);
                loanAlbum.setLoanId(loanId);
                loanAlbumMapper.insert(loanAlbum);
            });
        }
        return AjaxResult.success();
    }

    @Override
    public synchronized AjaxResult insuranceInput(InsuranceInfoBo insuranceInfoBo) {
        long loanId = Long.parseLong(insuranceInfoBo.getLoanId());
        Optional<LoanStatus> optionalLoanStatus = loanStatusMapper
            .selectByLoanId(loanId);
        LoanStatus loanStatus = optionalLoanStatus
            .orElseThrow(() -> new LoanParameterException("业务状态数据异常请联系管理员"));
        if (InsuranceInfoStatus.INIT.status != loanStatus.getInsuranceInfoStatus()) {
            return AjaxResult.error("当前状态不可提交");
        }

        loanStatus.setInsuranceInfoId(SecurityUtils.getLoginUserId());
        loanStatus.setInsuranceInfoStatus(insuranceInfoBo.getOperatorStatus());
        loanStatus.setInsuranceInfoTime(LocalDateTime.now());
        loanStatusMapper.updateById(loanStatus);

        Optional<LoanInsurance> loanInsuranceOptional = loanInsuranceMapper.selectByLoanId(loanId);
        LoanInsurance loanInsurance = loanInsuranceOptional
            .orElseThrow(() -> new LoanParameterException("业务数据保险数据异常"));

        BeanUtils.copyBeanProp(loanInsurance, insuranceInfoBo);
        loanInsuranceMapper.updateById(loanInsurance);

        LoanAlbum loanAlbumDelete = new LoanAlbum();
        loanAlbumDelete.setLoanId(loanId);
        loanAlbumDelete.setType(LoanAlbumType.CAR_INFO.type);
        QueryWrapper<LoanAlbum> queryWrapper = new QueryWrapper<>(loanAlbumDelete);
        loanAlbumMapper.delete(queryWrapper);
        List<LoanAlbumVo> carInfoAlbums = insuranceInfoBo.getCarInfoAlbums();
        if (null != carInfoAlbums) {
            carInfoAlbums.forEach(carInfoAlbum -> {
                LoanAlbum loanAlbum = new LoanAlbum();
                loanAlbum.setUrl(carInfoAlbum.getDbUrl());
                loanAlbum.setType(LoanAlbumType.CAR_INFO.type);
                loanAlbum.setLoanId(loanId);
                loanAlbumMapper.insert(loanAlbum);
            });
        }
        return AjaxResult.success();
    }
}
